package com.example.locationdemo;

import com.example.locationdemo.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.hiviewdfx.HiLog;
import ohos.location.Location;
import ohos.location.Locator;
import ohos.location.LocatorCallback;
import ohos.location.RequestParam;

public class MainAbility extends Ability {
    Locator locator = null;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        requestPermission();
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == 0) {
                // 权限被授予
                locator = new Locator(getContext());
                RequestParam requestParam = new RequestParam(RequestParam.SCENE_NAVIGATION, 0, 0);

                LocatorCallback callback = new LocatorCallback() {
                    @Override
                    public void onLocationReport(Location location) {
                        // 位置信息报告
                        HiLog.info(null, "位置信息：" + location.toString());
                    }

                    @Override
                    public void onStatusChanged(int i) {
                        // 状态改变回调
                    }

                    @Override
                    public void onErrorReport(int i) {
                        // 异常报告
                    }
                };
                locator.startLocating(requestParam, callback);
            } else {
                // 权限被拒绝
            }
        }
    }

    void requestPermission() {
        if (verifySelfPermission("ohos.permission.LOCATION") != 0) {
            if (canRequestPermission("ohos.permission.LOCATION")) {
                requestPermissionsFromUser(new String[] {"ohos.permission.LOCATION"}, 1);
            }
        }
    }
}
